<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="学年" prop="schoolYear">
        <el-select v-model="queryParams.schoolYear" placeholder="请选择学年" clearable :style="{ width: '100%' }">
          <el-option v-for="(item, index) in semesterYearList" :key="index" :label="item.schoolYear"
            :value="item.schoolYear" :disabled="item.disabled"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="学院专业" prop="selectId">
        <el-cascader :props="props" :show-all-levels="false" v-model="selectId" placeholder="请选择校区/学院/专业" />
      </el-form-item>

      <el-form-item label="班级" prop="gradeName">
        <el-input v-model="queryParams.gradeName" placeholder="请输入班级" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="学号" prop="sno">
        <el-input v-model="queryParams.sno" placeholder="请输入学号" clearable @keyup.enter.native="handleQuery"
          oninput="value=value.replace(/[^\d]/g,'')" :maxlength="11" />
      </el-form-item>

      <el-form-item label="姓名" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['backend:studentinfo:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport"
          v-hasPermi="['backend:studentinfo:import']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['backend:studentinfo:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="studentinfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="学号" align="center" prop="sno" />
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="班级名称" align="center" prop="gradeName" />
      <el-table-column label="性别" align="center" prop="gender">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.stu_student_sex" :value="scope.row.gender" />
        </template>
      </el-table-column>
      <el-table-column label="电话号码" align="center" prop="phone" />
      <el-table-column label="年级" align="center" prop="schoolYear" />
      <el-table-column label="邮箱" align="center" prop="mail" />
      <el-table-column label="家庭地址" align="center" prop="location" />
      <el-table-column label="是否在校" align="center" prop="isAtSchool">
        <template slot-scope="scope">
          <el-tag v-if=" scope.row.isAtSchool == 0">是</el-tag>
          <el-tag v-if=" scope.row.isAtSchool == 1" type="warning">否</el-tag>
          <el-tag v-if=" scope.row.isAtSchool == 2" type="danger">毕业</el-tag>
          <!-- <span>{{ scope.row.isAtSchool == 0 ? '是' : scope.row.isAtSchool == 1 ? '否' : '毕业' }}</span> -->
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['backend:studentinfo:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['backend:studentinfo:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改学生信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="学号" prop="sno">
          <el-input v-model="form.sno" placeholder="请输入学号" oninput="value=value.replace(/[^\d]/g,'')" :maxlength="11" />
        </el-form-item>

        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>

        <el-form-item label="年级" prop="schoolYear">
          <el-select v-model="form.schoolYear" placeholder="请选择年级" filterable clearable :style="{ width: '100%' }"
            @change="changeYear" @clear="clearToGrade">
            <el-option v-for="(item, index) in semesterYearList" :key="index" :label="item.schoolYear + '级'"
              :value="item.schoolYear" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="学院" prop="collegeId">
          <el-select v-model="form.collegeId" placeholder="请选择学院" filterable clearable :style="{ width: '100%' }"
            @change="changeCollege" @clear="clearCollege">
            <el-option v-for="(item, index) in collegeList" :key="index" :label="item.name" :value="item.id"
              :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="专业" prop="majorId">
          <el-select v-model="form.majorId" placeholder="请选择专业" filterable clearable :style="{ width: '100%' }"
            @change="changeMajor" @clear="clearToGrade">
            <el-option v-for="(item, index) in majorList" :key="index" :label="item.name" :value="item.id"
              :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="班级" prop="gradeId">
          <el-select v-model="form.gradeId" placeholder="请选择班级" filterable clearable :style="{ width: '100%' }"
            @change="changeGrade">
            <el-option v-for="(item, index) in gradeList" :key="index" :label="item.name" :value="item.id"
              :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio-button :label="1">男</el-radio-button>
            <el-radio-button :label="0">女</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="电话号码" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入电话号码" oninput="value=value.replace(/[^\d]/g,'')"
            :maxlength="11" />
        </el-form-item>

        <el-form-item label="邮箱" prop="mail">
          <el-input v-model="form.mail" placeholder="请输入邮箱" />
        </el-form-item>

        <el-form-item label="家庭地址" prop="location">
          <el-input type="textarea" :rows="3" v-model="form.location" placeholder="请输入家庭地址" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" :modal-append-to-body="false"
      :close-on-click-modal="false">
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的学生数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
            @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStudentinfo, getStudentinfo, delStudentinfo, addStudentinfo, updateStudentinfo } from "@/api/backend/studentinfo";
import editTable from '../../tool/gen/editTable.vue';
import { allListCampus } from "@/api/backend/campus";
import { allListCollege } from "@/api/backend/college";
import { allListMajor } from "@/api/backend/major";
import { allListGrade } from "@/api/backend/grade";
import { listSchoolYearList } from "@/api/backend/semester";
import { getToken } from "@/utils/auth";
// 导入模板接口importTemplate
import { importTemplate } from "@/api/system/user";

export default {
  components: { editTable },
  name: "Studentinfo",
  dicts: ['stu_student_sex'],
  data() {
    return {
      forbiddenTime: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 8.64e7;
        },
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学生信息表格数据
      studentinfoList: [],
      // 学院信息数据
      collegeList: [],
      //校区信息数据
      campusList: [],
      // 专业信息数据
      majorList: [],
      // 年级下拉框
      semesterYearList: [],
      // 学院下拉框
      collegeList: [],
      selCollegeList: [],
      collegeListBack: [],
      // 专业下拉框
      majorList: [],
      selMajorList: [],
      majorListBack: [],
      // 班级下拉框
      gradeList: [],
      gradeListBack: [],
      // 学生信息表格数据
      studentinfoList: [],
      // 校区/学院/专业Id
      selectId: null,
      // 查看是否是添加还是删除
      addOrUpdete: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/backend/studentinfo/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        gradeName: null,
        schoolYear: null,
        sno: null,
        name: null,
        phone: null,
        campusId: null
      },
      // 表单参数
      form: {
        gender: 0,
        graduateStatus: 0,
        accountStatus: 0,
      },
      schoolYearOptions: [],
      // 表单校验
      rules: {
        sno: [{
          required: true,
          message: '请输入学号',
          trigger: 'change'
        }],
        name: [{
          required: true,
          message: '请输入学生姓名',
          trigger: 'change'
        }],
        schoolYear: [{
          required: true,
          message: '请输入年级',
          trigger: 'change'
        }],
        gender: [{
          required: true,
          message: '请输入姓名',
          trigger: 'change'
        }],
        phone: [{
          required: true,
          message: '请输入电话号码',
          trigger: 'change'
        }],
        mail: [{
          required: true,
          message: '请输入邮箱',
          trigger: 'change'
        }],
        location: [{
          required: true,
          message: '请输入家庭地址',
          trigger: 'change'
        }],
        campusId: [{
          required: true,
          message: '请选择校区',
          trigger: 'change'
        }],
        collegeId: [{
          required: true,
          message: '请选择学院',
          trigger: 'change'
        }],
        majorId: [{
          required: true,
          message: '请选择专业',
          trigger: 'change'
        }],
        gradeId: [
          { required: true, message: "班级不能为空", trigger: "change" }
        ],
        majorName: [{
          required: true,
          message: '请输入专业名称',
          trigger: 'change'
        }],
      },
      props: {
        lazy: true,
        checkStrictly: true,
        expandTrigger: 'hover',
        lazyLoad(node, resolve) {
          var nodes = [];
          this.loading = true;
          const { level } = node;
          switch (level) {
            // 选择校区
            case 0:
              allListCampus().then(response => {
                this.campusList = response.rows;
                // 将列表中的数据以给定格式赋给nodes
                nodes = this.campusList.map(item => ({
                  value: item.id,
                  label: item.name,
                  leaf: level >= 2
                }));
                // 通过调用resolve将子节点数据返回，通知组件数据加载完成
                // 子节点的数据会保存在node下的children中
                resolve(nodes);
                this.loading = false;
                allListCollege().then(response => {
                  this.selCollegeList = response.rows;
                  this.collegeList = response.rows;
                  this.collegeListBack = response.rows;
                });
                allListMajor().then(response => {
                  this.selMajorList = response.rows;
                  this.majorList = response.rows;
                  this.majorListBack = response.rows;
                });
              });
              break;
            // 选择学院
            case 1:
              // 将列表中条件符合的数据赋给nodes
              nodes = this.selCollegeList.filter(item => {
                if (item.campusId == node.data.value) {
                  return true
                }
              });
              // 将nodes的格式进行更改，改为给定的格式
              nodes = nodes.map(item => ({
                value: item.id,
                label: item.name,
                leaf: level >= 2
              }))
              // 通过调用resolve将子节点数据返回，通知组件数据加载完成
              resolve(nodes);
              this.loading = false;
              break;
            // 选择专业
            case 2:
              // 将列表中条件符合的数据赋给nodes
              nodes = this.selMajorList.filter(item => {
                if (item.collegeId == node.data.value) {
                  return true
                }
              });
              // 将nodes的格式进行更改，改为给定的格式
              nodes = nodes.map(item => ({
                value: item.id,
                label: item.name,
                leaf: level >= 2
              }))
              // 通过调用resolve将子节点数据返回，通知组件数据加载完成
              resolve(nodes);
              this.loading = false;
              break;
            default:
              // 通过调用resolve将子节点数据返回，通知组件数据加载完成
              resolve(nodes);
              this.loading = false;
              break;
          }
        },
      }
    };
  },
  created() {
    this.getList();
    this.refData();
  },
  methods: {
    // 刷新数据
    refData() {
      this.getCampusListAll();
      this.getCollegeListAll();
      this.getMajorListAll();
      this.getGradeListAll();
      this.getSemesterYearListAll();
    },

    // *************************** 校区下拉框 ***************************
    /** 查询校区列表-全部 */
    getCampusListAll() {
      this.loading = true;
      allListCampus().then(response => {
        this.campusList = response.rows;
        this.loading = false;
      });
    },
    // *************************** 校区下拉框 ***************************



    // *************************** 学院下拉框 ***************************
    /** 查询学院列表-全部 */
    getCollegeListAll() {
      this.loading = true;
      allListCollege().then(response => {
        this.collegeList = response.rows;
        this.collegeListBack = response.rows;
        this.loading = false;
      });
    },
    // 改变学院下拉框选项
    changeCollege() {
      this.clearCollege()
      this.majorList = [];
      this.gradeList = [];
      this.forMajorList();
      this.forGradeList();
    },
    // 清除学院下拉框
    clearCollege() {
      delete this.form["majorId"];
      this.majorList = this.majorListBack;
      this.clearToGrade();
    },
    // *************************** 学院下拉框 ***************************



    // *************************** 专业下拉框 ***************************
    /** 查询专业列表-全部 */
    getMajorListAll() {
      this.loading = true;
      allListMajor().then(response => {
        this.majorList = response.rows;
        this.majorListBack = response.rows;
        this.loading = false;
      });
    },
    // 改变专业下拉框选项
    changeMajor(data) {
      this.gradeList = [];
      delete this.form["gradeId"];
      this.gradeListBack.forEach(item => {
        if (item.majorId == data) {
          if (!!this.form.schoolYear && item.schoolYear == this.form.schoolYear) {
            this.gradeList.push(item);
          } else if (!this.form.schoolYear) {
            this.gradeList.push(item);
          }
        }
      });
      for (let major = 0; major < this.majorList.length; major++) {
        if (this.majorList[major].id == this.form.majorId) {
          this.form.collegeId = this.majorList[major].collegeId;
          break;
        }
      }
      this.forMajorList();
    },
    // 循环专业列表
    forMajorList() {
      this.majorList = [];
      this.majorListBack.forEach(item => {
        if (item.collegeId == this.form.collegeId) {
          this.majorList.push(item);
        }
      })
    },
    // *************************** 专业下拉框 ***************************



    // *************************** 班级下拉框 ***************************
    /** 查询班级列表-全部 */
    getGradeListAll() {
      this.loading = true;
      allListGrade().then(response => {
        this.gradeList = response.rows;
        this.gradeListBack = response.rows;
        this.loading = false;
      });
    },
    // 选中班级下拉框选项
    changeGrade(data) {
      for (let grade = 0; grade < this.gradeList.length; grade++) {
        if (this.gradeList[grade].id == data) {
          this.form.schoolYear = this.gradeList[grade].schoolYear;
          this.form.majorId = this.gradeList[grade].majorId;
          break;
        }
      }
      for (let major = 0; major < this.majorList.length; major++) {
        if (this.majorList[major].id == this.form.majorId) {
          this.form.collegeId = this.majorList[major].collegeId;
          break;
        }
      }
      this.forMajorList()
      this.forGradeList()
    },
    // 清除班级下拉框的数据
    clearToGrade() {
      if (!!this.form.gradeId) {
        // this.form.gradeId = null;
        delete this.form["gradeId"];
      }
      this.forGradeList();
    },
    // 循环班级列表
    forGradeList() {
      this.gradeList = [];
      if (!!this.form.majorId) {
        this.gradeListBack.forEach(item => {
          if (item.majorId == this.form.majorId) {
            if (!!this.form.schoolYear && item.schoolYear == this.form.schoolYear) {
              this.gradeList.push(item);
            } else if (!this.form.schoolYear) {
              this.gradeList.push(item);
            }
          }
        })
      } else {
        this.gradeListBack.forEach(item => {
          for (let grade = 0; grade < this.majorList.length; grade++) {
            if (item.majorId == this.majorList[grade].id) {
              if (!!this.form.schoolYear && item.schoolYear == this.form.schoolYear) {
                this.gradeList.push(item);
                break;
              } else if (!this.form.schoolYear) {
                this.gradeList.push(item);
                break;
              }
            }
          }
        })
      }
    },
    // *************************** 班级下拉框 ***************************



    // *************************** 学期下拉框 ***************************
    /** 查询列表-全部 */
    getSemesterYearListAll() {
      this.loading = true;
      listSchoolYearList().then(response => {
        this.semesterYearList = response.rows;
        this.loading = false;
      });
    },
    // 改变学期下拉框
    changeYear(data) {
      this.gradeList = [];
      delete this.form["gradeId"];
      for (let i = 0; i <= this.majorList.length - 1; i++) {
        for (let j = 0; j <= this.gradeListBack.length - 1; j++) {
          if (this.gradeListBack[j].schoolYear == data) {
            if (!!this.form.majorId && this.gradeListBack[j].majorId == this.form.majorId) {
              this.gradeList.push(this.gradeListBack[j]);
            } else if (!this.form.majorId && this.majorList[i].id == this.gradeListBack[j].majorId) {
              this.gradeList.push(this.gradeListBack[j]);
            }
          }
        }
      }
    },
    // *************************** 学期下拉框 ***************************



    /** 查询学生信息列表 */
    getList() {
      this.loading = true;
      listStudentinfo(this.queryParams).then(response => {
        // console.log(response);
        this.studentinfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sno: null,
        name: null,
        gradeId: null,
        graderName: null,
        gender: 1,
        password: null,
        phone: null,
        schoolYear: null,
        mail: null,
        location: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      if (this.selectId != null) {
        this.queryParams.campusId = this.selectId[0]
        this.queryParams.collegeId = this.selectId[1]
        this.queryParams.majorId = this.selectId[2]
      }
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.selectId = null;
      this.queryParams.campusId = null;
      this.queryParams.collegeId = null;
      this.queryParams.majorId = null;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.addOrUpdete = 0;
      this.refData();
      this.reset();
      this.open = true;
      this.title = "添加学生信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      if (row.isAtSchool == 2) {
        this.$message({
          message: '该学生已经毕业!',
          type: 'warning'
        });
      } else {
        this.addOrUpdete = 1;
        this.refData();
        this.reset();
        this.form = JSON.parse(JSON.stringify(row));
        this.open = true;
        this.title = "修改学生信息";
        this.changeGrade(this.form.gradeId)
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateStudentinfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStudentinfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除学生信息编号为"' + ids + '"的数据项？').then(function () {
        return delStudentinfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('backend/studentinfo/export', {
        ...this.queryParams
      }, `学生信息_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "学生信息导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('backend/studentinfo/importTemplate', {
      }, `学生导入模板${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  }
};
</script>
